package top.superflow.utils

import java.io.{File, FileInputStream, FileOutputStream}

import org.springframework.util.FileCopyUtils
import top.superflow.exception.RequestUnsupportedException
import top.superflow.lang.StringUtils
import top.superflow.log.Loggable

import scala.io.Source

object FileUtils extends Loggable{


  def readText(file : File) : String = {
    if(file == null){
      logger.warn("The file is null")
      return StringUtils.EMPTY
    }

    if(!file.exists()){
      logger.warn("The file {} doesn't exist", file.getAbsoluteFile)
      return StringUtils.EMPTY
    }

    val source = Source.fromFile(file)
    try source.mkString finally source.close()

  }


  def getFile(file : Any) : File = {
    file match {
      case fpath : String => {
        getFile(new File(fpath))
      }

      case fl : File => {
        fl
      }

      case _ => {
        throw new RequestUnsupportedException(file)
      }
    }
  }

  def copy(source: String, targetDirPath: String): Unit ={
    if(StringUtils.isBlank(source)){
      logger.warn("The source should not be blank to copy")
      return
    }

    if(StringUtils.isBlank(targetDirPath)){
      logger.warn("The target directory should not be blank to copy")
      return
    }

    val sourceFile = new File(source)
    if(!sourceFile.exists()){
      logger.warn("The source file {} doesn't exist", source)
      return
    }

    val targetDir = new File(targetDirPath)
    if(!targetDir.exists()){
      targetDir.createNewFile()
    }

    if(!targetDir.isDirectory){
      logger.warn("The target directory {} is not a directory", targetDirPath)
      return
    }

    val targetFilePath = targetDirPath + "/" + sourceFile.getName

    val targetFile = new File(targetFilePath)
    targetFile.deleteOnExit()

    FileCopyUtils.copy(new FileInputStream(sourceFile), new FileOutputStream(targetFile))
  }

  def isFile(file : Any) : Boolean = {
    file match {
      case fpath: String => {
        return new File(fpath).exists()
      }

      case fl: File => {
        fl.exists()
      }

      case _ => {
        return false
      }
    }
  }
}
